#!/bin/bash
# This script pre-processes the Fortran source code for classic flang 7.0.1, Huawei Bisheng flang
# 1.3.3, NVIDIA nvfortran 22.3, and AOCC 3.2.0 flang, which raise a false positive error of
# out-bound subscripts when invoked with the -Mbounds flag.
# See https://github.com/flang-compiler/flang/issues/1238 and
# https://forums.developer.nvidia.com/t/bug-in-nvfortran-22-3-false-positive-of-out-bound-subscripts

DIR="$(realpath "$1")"
LINALG="$DIR/common/linalg.f90"
POWALG="$DIR/common/powalg.f90"
LINGEO="$DIR/lincoa/geometry.f90"

if ! basename "$DIR" | grep -q ".test\|test." || ! [[ -d "$DIR" ]] ; then
    printf "\n%s is not a testing directory.\n\nExit.\n\n" "$DIR"
    exit 1
fi

if [[ -f "$LINALG" ]] ; then
    OLDSTR="x(i) = (b(i) - inprod(A(i, 1:i - 1), x(1:i - 1))) / A(i, i)"
    NEWSTR="x(i) = (b(i) - dot_product(A(i, 1:i - 1), x(1:i - 1))) / A(i, i)"
    sed -i "s|$OLDSTR|$NEWSTR|g" "$LINALG"
    OLDSTR="x(i) = (b(i) - inprod(A(i, i + 1:n), x(i + 1:n))) / A(i, i)"
    NEWSTR="x(i) = (b(i) - dot_product(A(i, i + 1:n), x(i + 1:n))) / A(i, i)"
    sed -i "s|$OLDSTR|$NEWSTR|g" "$LINALG"
    OLDSTR="x(i) = (b(i) - inprod(R(i, i + 1:n), x(i + 1:n))) / R(i, i)"
    NEWSTR="x(i) = (b(i) - dot_product(R(i, i + 1:n), x(i + 1:n))) / R(i, i)"
    sed -i "s|$OLDSTR|$NEWSTR|g" "$LINALG"
fi

if [[ -f "$POWALG" ]] ; then
    OLDSTR="Anew = reshape(\[A(:, 1:i - 1), A(:, i + 1:n), A(:, i)\], shape(Anew))"
    NEWSTR="if (i<n) then \n if (i <= 1) then \n Anew = reshape(\[A(:, i + 1:n), A(:, i)\], shape(Anew))\
        \n else \n Anew = reshape(\[A(:, 1:i - 1), A(:, i + 1:n), A(:, i)\], shape(Anew)) \n end if \n end if"
    sed -i "s|$OLDSTR|$NEWSTR|g" "$POWALG"
    OLDSTR="Anew = reshape(\[Anew(:, 1:i - 1), Anew(:, i + 1:n), Anew(:, i)\], shape(Anew))"
    NEWSTR="if (i<n) then \n if (i <= 1) then \n Anew = reshape(\[Anew(:, i + 1:n), Anew(:, i)\], shape(Anew))\
        \n else \n Anew = reshape(\[Anew(:, 1:i - 1), Anew(:, i + 1:n), Anew(:, i)\], shape(Anew)) \n end if \n end if"
    sed -i "s|$OLDSTR|$NEWSTR|g" "$POWALG"
fi

if [[ -f "$LINGEO" ]] ; then
    OLDSTR="pglag = matprod(qfac(:, nact + 1:n), matprod(glag, qfac(:, nact + 1:n)))"
    NEWSTR="pglag = matmul(qfac(:, nact + 1:n), matmul(glag, qfac(:, nact + 1:n)))"
    sed -i "s|$OLDSTR|$NEWSTR|g" "$LINGEO"
fi

exit 0
